package com.itheima.sh.controller;

import com.itheima.sh.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 问题分析：
 * 1、IP和端口  硬编码
 * 2、不能负载均衡的调用服务提供方
 * 3、服务消费方不能感知服务提供方的健康状态
 */
@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") String id){

//        List<ServiceInstance> instanceList = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instanceList.get(0);
//
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();

//        String url = "http://"+host+":"+port+"/user/" + id;

        // 在Eureka Server中注册的服务的名称
        String url = "http://user-service/user/" + id;

        System.out.println("我是 Master...");

        // 调用RestTemplate的getForObject方法，指定url地址和返回值类型
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }
}
